
/*
 * Copyright (C) 2010 Bitglue. All rights reserved.
 *
 * $Id: JVMInfoController.java bself $
 */

package com.bitglue.web.admin.webmvc;

import com.bitglue.web.admin.util.TransformUtils;
import com.bitglue.web.admin.util.XmlTreeUtils;
import com.bitglue.web.admin.webmvc.model.JVMInfoModel;

import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import org.w3c.dom.Element;

/**
 * JVMInfoController for displaying JVM info.
 * @author Bryan Patrick Self
 */
@Controller("jvmInfoController")
@SessionAttributes(types = JVMInfoModel.class)
public class JVMInfoController {

    protected final Logger log = Logger.getLogger(getClass());

    @RequestMapping(value = "/jvminfo.do", method = RequestMethod.GET)
    public ModelAndView jvmInfoSetup(HttpServletRequest req) {
        log.debug("creating new jvm info model for client "
          + req.getRemoteAddr());
        JVMInfoModel infoModel = new JVMInfoModel();
        return new ModelAndView("jvminfo", "infoModel", infoModel);
    }

    @RequestMapping(value = "/getJvmProps.do")
    public void getJVMProps(HttpServletRequest req,
      HttpServletResponse resp) throws Exception {
        resp.setContentType("text/xml");
        log.debug("retrieving system properties for client "
          + req.getRemoteAddr());

        int id = 1;
        Element root = XmlTreeUtils.newTree();
        Properties sysProps = System.getProperties();
        for (Enumeration keys = sysProps.keys(); keys.hasMoreElements();) {
            String key = (String)keys.nextElement();
            String val = (String)sysProps.get(key);
            if (!key.endsWith(".path")) {
                XmlTreeUtils.newLeaf(root, id++, key + " : " + val);
                continue;
            }
            Element pe = XmlTreeUtils.newLeaf(root, id++, key + " : ");
            for (String path : val.split(":"))
                XmlTreeUtils.newLeaf(pe, id++, path);
        }
        TransformUtils.transform(root, resp.getOutputStream());
    }

}
